home *** CD-ROM | disk | FTP | other *** search
- Path: nyx10.cs.du.edu!not-for-mail
- From: cwyles@nyx10.cs.du.edu (Carl Wyles)
- Newsgroups: comp.lang.c
- Subject: Re: Sorting a Binary File
- Date: 15 Apr 1996 19:19:27 -0600
- Organization: University of Denver, Math/CS Dept.
- Message-ID: <4kusiv$pgt@nyx10.cs.du.edu>
- References: <4krpuf$jfp@news1.sympatico.ca>
- NNTP-Posting-Host: nyx10.nyx.net
- X-Newsreader: NN version 6.5.0 #3 (NOV)
-
- Gisele Swinson <gisele.swinson@sympatico.ca> writes:
-
- >I have declared a structure as follows:
-
- >#define max 5
-
- >struct customer
- >{
- > int seatno;
- > char lastname[15];
- >} Customer[max];
-
- >I have also initialized the structure as the seat numbers 1-5 and the last
- >name as blank
-
- >My program summarized is I enter a seat number then enter the name, when I
- >cam finished, save the data to a binary file. I want to sort the
- >structures in last name order. I tried using bubble sort but I'm not
- >being very successful.
-
- >This is what I tried:
-
- >for(pass=1; pass<max; pass++)
- > for(i = 0; i<max-1; i++)
-
- > if(Customer[i].lastname > Customer[i+1].lastname)
- > {
- > temp = Customer[i];
- > Customer[i] = Customer[i+1];
- > Customer[i+1] = temp;
- > }
- Above code is undefined on most C compilers because of the way strings
- are defined. I am not sure what the C++ compilers would do.
- A string in C is nothing more than and array of characters. This is what
- causes most problems with string comparison.
-
- > printf("\nSorted customer list");
- > printf("\nSeat number Customer Name"):
- >
- > for(x=0; x<max; x++)
- > printf("\n%2d\t %s", Customer[x].seatno, Customer[x].lastname);
-
- Well, I would suggest the following for starters...
-
- /* sort - indexed bubble */
- for( x = 0; x < filled; x++ ) {
- idx[ x ] = x; /* set up index to values */
- }
- /* filled = number of elements with data */
- for( pass = 0; pass < filled - 1; pass++ ) {
- for( x = pass; x < filled; x++ ) {
- /* use strcmp to compare strings */
- if( strcmp( Customer[ idx[ x + 1 ] ].lastname,
- Customer[ idx[ x ] ].lastname ) < 0 )
- /* only move the index values */
- temp = idx[ x ];
- idx[ x ] = idx[ x + 1 ];
- idx[ x + 1 ] = temp;
- }
- }
- }
-
- printf( "Sorted list" );
- for( x = 0; x < filled; x++ ) {
- printf("\n%2d\t %s", Customer[ idx[ x ] ].seatno,
- Customer[ idx[ x ] ].lastname );
- }
-
- I said this was for starters :)
-
- If you want to make it faster use some other type of sort routine. QSORT
- is usually in most C libraries. You want to use an index because it is
- faster than moving the whole data item.
-
- --
- >>>>> All flames sent to Demon Dragon familiar for appropriate response <<<<<
- cwyles@nyx10.cs.du.edu | My words are the amalgamation of my experiences only
- Good advice is ignored. Ok advice is used. Bad advice is flamed forever.
-